import {DependencyList, useEffect, useState} from 'react';
import {ApiResult, DetailsOperateResult} from "@/global";

/** 详情组件属性 */
export interface DetailsProps<T> {
  /** 对话框是否可见 */
  visible: boolean;
  /** 服务端读取数据 */
  onDetails: () => Promise<ApiResult<T>>;
  /** 组件依赖项 */
  deps?: DependencyList;
}

/** 详情操作组件 */
function useDetails<Model>(props: DetailsProps<Model>): DetailsOperateResult<Model> {
  const {visible, onDetails, deps = []} = props;
  if (!visible) {
    return {loading: false};
  }

  const [loading, setLoading] = useState<boolean>(false);
  const [model, setModel] = useState<Model>();

  useEffect(() => {
    if (!onDetails) return;
    setLoading(true);
    onDetails().then((r) => {
      setLoading(false);
      if (r.success && r.data) {
        //读取成功后设置数据对象,并设置组件显示状态为true
        setModel(r.data);
      }
    }).catch(() => setLoading(false));
  }, deps);

  return {
    loading,
    model,
  };
}

export default useDetails;
